﻿using System;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using PmuRegistry.Silverlight.ModalDialogs;
using PmuRegistry.Silverlight.PmuRegistryDataServiceProxy;
using PmuRegistry.Silverlight.Utilities;
using System.Collections.Generic;
using System.Windows.Media.Animation;

namespace PmuRegistry.Silverlight.Pages.Manage
{
	public partial class Companies : Page
	{
		PhasorDataServiceClient m_client;
		bool m_inEditMode = false;
		int m_companyID = 0;

		public Companies()
		{
			InitializeComponent();
			m_client = Common.GetPhasorDataServiceClient();
			m_client.GetCompanyListCompleted += new EventHandler<GetCompanyListCompletedEventArgs>(client_GetCompanyListCompleted);
			m_client.SaveCompanyCompleted += new EventHandler<SaveCompanyCompletedEventArgs>(client_SaveCompanyCompleted);
			m_client.GetTimeZonesCompleted += new EventHandler<GetTimeZonesCompletedEventArgs>(client_GetTimeZonesCompleted);
			m_client.GetInterconnectionsCompleted += new EventHandler<GetInterconnectionsCompletedEventArgs>(client_GetInterconnectionsCompleted);
			m_client.GetNercRegionsCompleted += new EventHandler<GetNercRegionsCompletedEventArgs>(client_GetNercRegionsCompleted);
			Loaded += new RoutedEventHandler(Companies_Loaded);
			ButtonSave.Click += new RoutedEventHandler(ButtonSave_Click);
			ButtonClear.Click += new RoutedEventHandler(ButtonClear_Click);
			ListBoxCompanyList.SelectionChanged += new SelectionChangedEventHandler(ListBoxCompanyList_SelectionChanged);
		}

		void client_GetNercRegionsCompleted(object sender, GetNercRegionsCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxNercRegion.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve NERC Regions", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboboxNercRegion.Items.Count > 0)
				ComboboxNercRegion.SelectedIndex = 0;
		}

		void client_GetInterconnectionsCompleted(object sender, GetInterconnectionsCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxInterconnection.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Interconnections", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboboxInterconnection.Items.Count > 0)
				ComboboxInterconnection.SelectedIndex = 0;
		}

		void client_GetTimeZonesCompleted(object sender, GetTimeZonesCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxTimeZone.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Time Zones", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboboxTimeZone.Items.Count > 0)
				ComboboxTimeZone.SelectedIndex = 0;
		}

		void client_SaveCompanyCompleted(object sender, SaveCompanyCompletedEventArgs e)
		{
			SystemMessages sm;
			if (e.Error == null)
			{
				ClearForm();
				sm = new SystemMessages(new Message() { UserMessage = e.Result, SystemMessage = string.Empty, UserMessageType = MessageType.Success },
						ButtonType.OkOnly);
			}
			else
			{
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Save Company Information", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
			}
			sm.Show();
			m_client.GetCompanyListAsync();	//refresh data to reflect changes.
		}
		
		void Companies_Loaded(object sender, RoutedEventArgs e)
		{
			GridCompanyDetail.DataContext = new Company();
		}
		
        void ListBoxCompanyList_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (ListBoxCompanyList.SelectedIndex >= 0)
			{
				Company selectedCompany = ListBoxCompanyList.SelectedItem as Company;
				ComboboxInterconnection.SelectedItem = new KeyValuePair<int, string>(selectedCompany.InterconnectionID, selectedCompany.InterconnectionName);
				ComboboxNercRegion.SelectedItem = new KeyValuePair<int, string>(selectedCompany.NercRegionID, selectedCompany.NercRegionName);
				ComboboxTimeZone.SelectedItem = selectedCompany.TimeZone;
				GridCompanyDetail.DataContext = selectedCompany;
				m_inEditMode = true;
				m_companyID = selectedCompany.ID;
			}
		}
		
        void ButtonClear_Click(object sender, RoutedEventArgs e)
		{
			Storyboard sb = new Storyboard();
			sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
			sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
			Storyboard.SetTarget(sb, ButtonClearTransform);
			sb.Begin();
			ClearForm();
		}

        void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            Storyboard sb = new Storyboard();
            sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
            sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
            Storyboard.SetTarget(sb, ButtonSaveTransform);
            sb.Begin();

            if (IsValid())
            {
                Company company = new Company();
                company.Acronym = TextBoxAcronym.Text.CleanText();
                company.MapAcronym = TextBoxMapAcronym.Text.CleanText();
                company.Name = TextBoxName.Text.CleanText();
                company.URL = TextBoxURL.Text.CleanText();
                company.InterconnectionID = ((KeyValuePair<int, string>)ComboboxInterconnection.SelectedItem).Key;
                company.NercRegionID = ((KeyValuePair<int, string>)ComboboxNercRegion.SelectedItem).Key;
                company.TimeZone = ((KeyValuePair<string, string>)ComboboxTimeZone.SelectedItem).Key;

                if (m_inEditMode == true && m_companyID != 0)
                {
                    company.ID = m_companyID;
                    m_client.SaveCompanyAsync(company, false);
                }
                else
                    m_client.SaveCompanyAsync(company, true);
            }
        }

        bool IsValid()
        {
            bool isValid = true;

            if (string.IsNullOrEmpty(TextBoxAcronym.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Acronym", SystemMessage = "Please provide valid Acronym for a comapny.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxAcronym.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (string.IsNullOrEmpty(TextBoxMapAcronym.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Map Acronym", SystemMessage = "Please provide valid Map Acronym for a company.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxMapAcronym.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (string.IsNullOrEmpty(TextBoxName.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Name", SystemMessage = "Please provide valid Name for a company.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxName.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            return isValid;
        }
		
        void client_GetCompanyListCompleted(object sender, GetCompanyListCompletedEventArgs e)
		{
			if (e.Error == null)
				ListBoxCompanyList.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Company List", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
		}
		
        void ClearForm()
		{
			GridCompanyDetail.DataContext = new Company();	//bind an empty object
			ComboboxTimeZone.SelectedIndex = 0;
			ComboboxNercRegion.SelectedIndex = 0;
			ComboboxInterconnection.SelectedIndex = 0;
			m_inEditMode = false;
			m_companyID = 0;
			ListBoxCompanyList.SelectedIndex = -1;
		}

		private void HyperlinkButtonContact_Click(object sender, RoutedEventArgs e)
		{
			int companyID = Convert.ToInt32(((HyperlinkButton)sender).Tag.ToString());
			string companyAcronym = ((HyperlinkButton)sender).Name;
			Contacts contacts = new Contacts(companyID, companyAcronym);
			contacts.Show();
		}

		// Executes when the user navigates to this page.
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			m_client.GetCompanyListAsync();
			m_client.GetTimeZonesAsync(false);
			m_client.GetNercRegionsAsync(false);
			m_client.GetInterconnectionsAsync(false);
		}
	}
}
